/**
 * 
 */
package com.hfjyz.exam.service;

import java.io.FileNotFoundException;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

import javax.servlet.http.HttpServletRequest;

import org.apache.poi.hssf.usermodel.HSSFCell;
import org.apache.poi.hssf.usermodel.HSSFRow;
import org.apache.poi.hssf.usermodel.HSSFSheet;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.ss.usermodel.DataFormatter;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.validation.BindException;
import org.springframework.web.multipart.MultipartFile;

import com.hfjyz.exam.dao.UserDao;
import com.hfjyz.exam.model.UserInfo;
import com.hfjyz.exam.util.CryptUtil;

/**
 *
 */
public class LoadUserServiceImpl extends AbstractServiceImpl implements
		LoadUserService {
	private UserDao userDao;

	@Transactional(rollbackFor = { Exception.class })
	@Override
	public void analyzeUserInfo(HttpServletRequest request,
			MultipartFile multipartFile, BindException errors) throws Exception {

		HSSFWorkbook workbook = null;
		try {
			workbook = new HSSFWorkbook(multipartFile.getInputStream());
		} catch (FileNotFoundException e) {
			errors.reject("error.loadnousertem", "failed loadquestion!");
			return;
		} catch (IOException e) {
			e.printStackTrace();
		}
		// 获得指定的sheet
		HSSFSheet sheet = workbook.getSheetAt(0);
		// 获得sheet总行数
		int rowCount = sheet.getLastRowNum();
		if (rowCount < 1) {
			return;
		}

		List<UserInfo> uis = new ArrayList<UserInfo>();
		// 遍历行row
		for (int rowIndex = 0; rowIndex <= rowCount; rowIndex++) {

			// 获得行对象
			HSSFRow row = sheet.getRow(rowIndex);
			if (null != row) {
				UserInfo ui = new UserInfo();
				ui.setIdCardNo(getCellString(row.getCell(0)));
				ui.setName(getCellString(row.getCell(1)));
				ui.setPassword(CryptUtil.encrypt(getCellString(row.getCell(2))));
				ui.setIdCardNo(getCellString(row.getCell(0)));
				uis.add(ui);
			}
		}
		userDao.addAll(uis);
	}

	private String getCellString(HSSFCell cell) {
		return new DataFormatter().formatCellValue(cell);
	}

	/**
	 * @return the userDao
	 */
	public UserDao getUserDao() {
		return userDao;
	}

	/**
	 * @param userDao
	 *            the userDao to set
	 */
	public void setUserDao(UserDao userDao) {
		this.userDao = userDao;
	}

}
